package org.openstreetmap.travelingsalesman.actions;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import org.openstreetmap.osm.Settings;
import org.openstreetmap.travelingsalesman.gui.MainFrame;
import org.openstreetmap.travelingsalesman.gui.ModifyProfileFrame;

public class ModifyProfile extends AbstractAction {

    /**
     * generated.
     */
    private static final long serialVersionUID = -8136640455463445179L;
    private File fileToBeModified = null;

    /**
     * Constructor for this action.
     */
    public ModifyProfile() 
    {
        super(MainFrame.RESOURCE.getString("Actions.ModifyProfile.Label"));
        putValue(Action.SHORT_DESCRIPTION, MainFrame.RESOURCE.getString("Actions.ModifyProfile.Description"));
    }

    /**
     * ${@inheritDoc}.
     */
    @Override
    public void actionPerformed(final ActionEvent e) 
    {
        JFileChooser fileChooser = new JFileChooser(new File(Settings.getInstance().get("traveling-salesman.loadFile.lastPath", ".")));
        fileChooser.setAcceptAllFileFilterUsed(true);
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.addChoosableFileFilter(new FileFilter() {

            @Override
            public boolean accept(final File file) {
                if (file.isDirectory())
                    return true;
                String fileName = file.getName().toLowerCase();
                return fileName.endsWith(".upx");
            }

            @Override
            public String getDescription() {
                return "UPX Profile File (.upx)";
            }
        });
        
        boolean condition = false;
        
        while(!condition)
        {
            int result = fileChooser.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) 
            {
                fileToBeModified = fileChooser.getSelectedFile();
                
                if(fileToBeModified.getAbsolutePath().indexOf(".upx")>0)
                {
                    condition=true;
                }
            }
            else
            {
                break;
            }
        }
        
        if(condition)
        {
            ModifyProfileFrame frame = new ModifyProfileFrame(fileToBeModified);
            frame.setDefaultCloseOperation(ModifyProfileFrame.DISPOSE_ON_CLOSE);
            frame.setTitle(MainFrame.RESOURCE.getString("ModifyProfile.Title"));
            frame.getContentPane().setPreferredSize(frame.getSize());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }
}